第14天的主題是MQTT(Message Queuing Telemetry Transport)介紹。MQTT是一個輕量級的、簡單的、高效的通訊協議,主要用於物聯網(IoT)應用中,在這裡我使用 Android 套件可以對訂閱的主題發出訊息或接收,接下來就來看看實作吧!!
dependencies {
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5'
}
public void connect(String brokerUrl, String clientId) {
try {
// 設置持久性層
MemoryPersistence persistence = new MemoryPersistence();
// 初始化MQTT客戶端
client = new MqttClient(brokerUrl, clientId, persistence);
// 設置連接選項
MqttConnectOptions connectOptions = new MqttConnectOptions();
connectOptions.setCleanSession(true);
// 連接到代理
client.connect(connectOptions);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
在MQTT中,消息推送通常稱為“發佈”。發佈是將消息發送到指定的主題。以下是一個發佈消息的示例:
public void publish(String topic, String message) {
try {
MqttMessage mqttMessage = new MqttMessage(message.getBytes());
client.publish(topic, mqttMessage);
} catch (MqttException e) {
e.printStackTrace();
}
}
public void subscribe(String topic) {
try {
client.subscribe(topic, 0);
} catch (MqttException e) {
e.printStackTrace();
}
}
public class MainActivity extends AppCompatActivity {
private MqttHandler mqttHandler;
private Button buttonOn;
private Button buttonOff;
private Button buttonSubscribe;
private Button buttonUnSubscribe;
private String brokerUrl = "tcp://broker.emqx.io";
private String clientId = "mqttx_01fa1dad";
private EditText publish_editText;
private EditText subscribe_editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOn = findViewById(R.id.on_button);
buttonOff = findViewById(R.id.off_button);
buttonSubscribe = findViewById(R.id.subscribe_button);
buttonUnSubscribe = findViewById(R.id.unsubscribe_button);
publish_editText = findViewById(R.id.publish_editText);
subscribe_editText = findViewById(R.id.subscribe_editText);
buttonOn.setOnClickListener(this::publishMessageOn);
buttonOff.setOnClickListener(this::publishMessageOff);
buttonSubscribe.setOnClickListener(this::subscribeToTopic);
buttonUnSubscribe.setOnClickListener(this::unSubscribeToTopic);
// 做mqtt連線
mqttHandler = new MqttHandler();
mqttHandler.connect(brokerUrl, clientId);
}
今天先講解到 Android 去連線 broker 和使用 MQTTX!!!!